package cn.com.qingz.modules.security;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.AbstractRememberMeManager;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.qingz.core.model.DefaultResp;
import cn.com.qingz.core.utils.MD5;
import cn.com.qingz.modules.user.model.Organization;
import cn.com.qingz.modules.user.model.User;
import cn.com.qingz.modules.user.service.OrganizationService;
import cn.com.qingz.modules.user.service.UserService;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.*;
import javax.crypto.spec.*;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * 安全认证
 * @author jiulong.hu
 */
@Controller
@RequestMapping("sys/authen")
public class AuthenController  extends CookieRememberMeManager{

    @Autowired
    private OrganizationService orgService;

    @Autowired
    private UserService userService;

    /**
     * 用户注销 (退出登陆)
     * @return
     */
    @RequestMapping(value = "logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

    /**
     * 用户登陆
     * @param username 用户名
     * @param password 密码
     * @return
     * @throws AuthenticationException
     */
    @RequestMapping(value = "login", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public DefaultResp<Map<String, Object>> login(String username, String password, HttpServletRequest request) throws AuthenticationException {
        System.out.println("调用登录");
        DefaultResp<Map<String, Object>> dr = new DefaultResp<Map<String, Object>>();

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(username);
        token.setPassword(password.toCharArray());
        token.setRememberMe(true);

        if (subject.isAuthenticated()) {
            //  throw new AlreadyLoggedException(SystemConstantes.RESULT_EXP, "已经登录，请勿重复登录");
        }
        subject.login(token); //登录
        if (!subject.isAuthenticated()) {
            System.out.println("未登陆成功");
            throw new AuthenticationException("未登陆成功");
        } else {
            System.out.println("登录成功");
        }

        HttpSession session = request.getSession();
        session.setAttribute("username", username);

        //		request.getSession().setAttribute("longin_user", user);
        //		String sessionID = request.getSession().getId();
        //    	String server = request.getServerName();
        //    	int port = request.getServerPort();
        //		return "index";

        Map<String, Object> value = new HashMap<String, Object>();
        value.put("token", new MD5().GetMD5Code(new Date().getTime() + username));
        value.put("username", username);
        value.put("logintime", new Date().getTime());

        dr.setData(value);
        return dr;
    }

    /**
     * 获取组织机构
     * @param pid
     * @return
     */
    @RequestMapping("/getOrgChildren")
    @ResponseBody
    public DefaultResp<List<Organization>> getOrgChildren(Long pid) {
        DefaultResp<List<Organization>> res = new DefaultResp<List<Organization>>();
        res.setData(orgService.getChildren(pid));
        return res;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("regist")
    @ResponseBody
    public DefaultResp<String> regist(User user) {
        DefaultResp<String> res = new DefaultResp<String>();
        userService.doRegister(user);
        return res;
    }

    void  test(){
        setCipherKey(Base64.decode("JVk3OvRmr3jB5VQSdyMFkeyRPO+NGNtbINTsiXtxgvM="));
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try{

            baos = new ByteArrayOutputStream();
            oos  =new ObjectOutputStream(baos) ;
            oos.writeObject(new User());
            byte[] bytes =baos.toByteArray();
            String a = Base64.encodeToString(encrypt(bytes));
            System.out.println(a);

        }catch (Exception ee){
            ee.printStackTrace();
        }
    }

    public static void main(String[] args) {
        AuthenController  authenController = new AuthenController();
        authenController.test();
    }

}
